package com.leslie.web.core.config;

import com.leslie.common.config.LeslieConfig;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;

/**
 * Swagger2的接口配置
 *
 * @author leslie
 */
@Configuration
public class SwaggerConfig {
    /**
     * 系统基础配置
     */
    @Autowired
    private LeslieConfig leslieConfig;

    /**
     * 自定义的 OpenAPI 对象
     */
    @Bean
    public OpenAPI customOpenApi() {
        return new OpenAPI().components(new Components()
                        // 设置认证的请求头
                        .addSecuritySchemes("apikey", securityScheme()))
                .addSecurityItem(new SecurityRequirement().addList("apikey"))
                .info(getApiInfo());
    }

    @Bean
    public SecurityScheme securityScheme() {
        return new SecurityScheme()
                .type(SecurityScheme.Type.APIKEY)
                .name("Authorization")
                .in(SecurityScheme.In.HEADER)
                .scheme("Bearer");
    }

    /**
     * 添加摘要信息
     */
    public Info getApiInfo() {
        return new Info()
                // 设置标题
                .title("接口文档")
                // 描述
                .description("描述：用于系统接口调试")
                // 作者信息
                .contact(new Contact().name("Leslie Lee"))
                // 版本
                .version("版本号:" + leslieConfig.getVersion());
    }

    // 定义一个HTTP方法顺序的映射表
    private static final Map<String, Integer> HTTP_METHOD_ORDER = new HashMap<>();
    static {
        HTTP_METHOD_ORDER.put("GET", 1);
        HTTP_METHOD_ORDER.put("POST", 2);
        HTTP_METHOD_ORDER.put("PUT", 3);
        HTTP_METHOD_ORDER.put("DELETE", 4);
        // 可以继续添加其他方法
    }

    @Bean
    public OperationCustomizer operationCustomizer() {
        return (operation, handlerMethod) -> {
            // 从handlerMethod中获取HTTP方法名（如 "GET", "POST"）
            String httpMethod = handlerMethod.getMethod().getAnnotation(RequestMapping.class).method()[0].name();
            // 根据映射表设置position
            Integer position = HTTP_METHOD_ORDER.get(httpMethod);
            if (position != null) {
                // 这里巧妙地将position设置到Operation的extensions属性中，Springdoc会识别它
                operation.addExtension("x-position", position);
            }
            return operation;
        };
    }

}
